import 'dart:io';

import 'package:environmental_les_app/common/net/net.dart';
import 'package:environmental_les_app/common/utils/utils.dart';
import 'package:flutter_clx_base/common/colours.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/widget/normal_dialog.dart';

class SelectImageBottomDialog extends StatelessWidget {
  final String? title;
  final String? iconPath;
  final Function onCallback;

  const SelectImageBottomDialog({
    super.key,
    this.title,
    this.iconPath,
    required this.onCallback,
  });

  @override
  Widget build(BuildContext context) {
    KeyBoardUtils.hideKeyboard();
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: Visibility(
            visible: !title.isNullOrEmpty(),
            child: Container(
              margin: const EdgeInsets.only(
                left: 18,
                right: 18,
              ),
              decoration: const BoxDecoration(
                  color: white,
                  borderRadius: BorderRadius.all(Radius.circular(10.0))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Column(
                    children: [
                      vGap18,
                      Text(
                        title ?? "",
                        style: const TextStyle(
                            fontSize: 16,
                            color: text000,
                            fontWeight: FontWeight.w500),
                      ),
                      vGap18,
                      Expanded(
                        child: ImageWidget.loadAssetImage(
                          iconPath,
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        vGap10,
        cardContainer(children: [
          buttonItem(
              title: "拍照",
              onTap: () {
                Get.back();
                _selectPic(ImageSource.camera, onCallback);
              }),
          const Divider(height: 1.0),
          buttonItem(
              title: "从相册选择",
              onTap: () {
                Get.back();
                _selectPic(ImageSource.gallery, onCallback);
              }),
        ]),
        vGap10,
        cardContainer(children: [
          buttonItem(
            title: "取消",
            onTap: () => Get.back(),
          )
        ]),
        vGap10,
      ],
    );
  }

  /// 圆角卡片
  cardContainer({required List<Widget> children}) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        color: white,
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Column(
        children: children,
      ),
    );
  }

  /// 按钮
  buttonItem({title, onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        constraints: const BoxConstraints(minHeight: 45.0),
        alignment: Alignment.center,
        child: Text(
          title ?? "",
          style: const TextStyle(
              fontSize: 14.0, color: text21, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  /// 选择和加载图片
  Future<void> _selectPic(ImageSource source, onSuccess) async {
    if (Platform.isIOS) {
      switch (source) {
        case ImageSource.gallery:
          _galleryIOS(source, onSuccess);
          break;
        case ImageSource.camera:
          _cameraIOS(source, onSuccess);
          break;
      }
    } else if (Platform.isAndroid) {
      // 安卓上传处理
      switch (source) {
        case ImageSource.gallery:
          _checkPhotos(source, onSuccess);
          break;
        case ImageSource.camera:
          _checkCamera(source, onSuccess);
          break;
      }
    }
  }

  _galleryIOS(ImageSource source, onSuccess) async {
    requestPermission(
        toSettingTip: "无法访问相册中的照片，请前往系统设置！",
        permissionList: [Permission.photosAddOnly, Permission.photos],
        onGranted: () => _uploadImage(source, onSuccess),
        onRefuse: () => ToastUtil.showToast("无法访问相册中的照片，请前往系统设置！"));
  }

  _cameraIOS(ImageSource source, onSuccess) async {
    // 相机
    requestPermission(
        toSettingTip: "无法访问相机，请前往系统设置！",
        permissionList: [Permission.camera],
        onGranted: () => _uploadImage(source, onSuccess),
        onRefuse: () => ToastUtil.showToast("无法访问相机，请前往系统设置！"));
  }

  Future<void> _uploadImage(ImageSource source, onSuccess) async {
    var image = await ImagePicker().pickImage(source: source, imageQuality: 20);
    // 未选择图片时 返回值为null，不需要增加提示信息
    if (image == null) {
      return;
    }
    // 图片选择成功时，调用上传图片到服务器的方法
    String url = await NetUtils.uploadImage(path: image.path);
    onSuccess(url);
  }

  // 相机或相册权限检测
  _checkCamera(source, onSuccess) async {
    if (!await checkPermissionCamera()) {
      // 没有权限
      showRequestPermissionDialog("是否允许访问您的相机，以便您上传图片信息", source, onSuccess);
    } else {
      // 有权限
      requestPermissionCamera(
        onGranted: () => _uploadImage(source, onSuccess),
      );
    }
  }

  _checkPhotos(source, onSuccess) async {
    if (!await checkPermissionPhotos()) {
      // 没有权限
      showRequestPermissionDialog("是否允许访问您的相册，以便您上传图片信息", source, onSuccess);
    } else {
      // 有权限
      requestPermissionPhotos(
        onGranted: () => _uploadImage(source, onSuccess),
      );
    }
  }

  // 拒绝提示对话框
  void refusePrompt(String str) {
    Get.dialog(NormalDialog(
      content: str,
      cancelBtnText: null,
      confirmBtnText: "去授权",
      onConfirm: () {
        openAppSettings();
      },
    ));
  }

  // 权限提示对话框
  void showRequestPermissionDialog(String content, source, onSuccess) {
    Get.dialog(NormalDialog(
      content: content,
      cancelBtnText: "拒绝",
      confirmBtnText: "同意授权",
      onConfirm: () {
        requestPermissionCamera(
          onGranted: () => _uploadImage(source, onSuccess),
        );
      },
    ));
  }
}
